﻿// owner 蒋家伟

#include "ListenApplicationEventHandler.h"

// std
#include <cassert>

// qt
#include <QThread>
#include <QApplication>

#include "IApplicationEventArgs.h"
#include "IApplicationEvent.h"
#include "Log.h"
#include "IApplication.h"


using namespace jsdk;

namespace
{
    ListenApplicationEventHandler s_ListenApplicationEventHandler;
    OwnerPtr<Dbg_Warn_Dlg> s_opDbg_Warn_Dlg = nullptr;
}

jsdk::Dbg_Warn_Dlg* jsdk::ListenApplicationEventHandler::get()
{
    if (QThread::currentThread() != QApplication::instance()->thread())
        return nullptr;

    if (s_opDbg_Warn_Dlg == nullptr)
    {
        assert(false && "DBG_WARN");
        return nullptr;
    }

    return s_opDbg_Warn_Dlg.get();
}

jsdk::ListenApplicationEventHandler::ListenApplicationEventHandler()
{
    IApplicationEvent::get()->registerHandler(this);
}

jsdk::ListenApplicationEventHandler::~ListenApplicationEventHandler()
{
    IApplicationEvent::get()->unRegisterHandler(this);
}

void jsdk::ListenApplicationEventHandler::On(const IArgs* pArgs)
{
    if (const IApplicationEventArgs* pApplicationEventArgs = dynamic_cast<const IApplicationEventArgs*>(pArgs))
    {
        if (pApplicationEventArgs->getApplicationStatus() == ApplicationStatus::AfterCreate)
        {
            // 设置日志路径
            LOG_DIR_(QString::fromStdWString(IApplication::applicationDirPath() + L"/Log"));
            // 调试窗口初始化
            s_opDbg_Warn_Dlg.swap(Dbg_Warn_Dlg::create());
        }
        else if (pApplicationEventArgs->getApplicationStatus() == ApplicationStatus::BeforeClose)
        {
            s_opDbg_Warn_Dlg.reset();
        }
    }
}